<template>
    <div class="group-chat-container">
        <!-- 聊天头部 -->
        <div class="chat-header">
            <el-button icon="ArrowLeft" circle @click="back"></el-button>
            <div class="chat-title">
            </div>
            <div class="header-actions">
                <el-button icon="Bell" circle @click="loadNoticeRes"></el-button>
                <el-button icon="Document" circle @click="loadFiles"></el-button>
                <el-button icon="More" circle @click="loadMember"></el-button>
            </div>
        </div>

        <!-- 聊天内容 -->
        <div class="chat-content" ref="chatContent">
            <div class="message-list">
                <div v-for="message in messages" :key="message.id" class="message-item"
                    :class="{ 'self': message.userNum === currentUser.number }">
                    <el-avatar :src="message.avatar"
                        class="avatar">{{ getSenderName(message.userNum).charAt(0) }}</el-avatar>
                    <div class="message-bubble">
                        <div class="message-sender">{{ getSenderName(message.userNum) }}</div>
                        <div class="message-content">
                            <template v-if="message.type === 'text'">{{ message.content }}</template>
                            <template v-if="message.type === 'notice'">
                                <el-tag type="info" size="small">通知</el-tag> {{ message.content }}
                            </template>
                            <template v-if="message.type === 'file'">
                                <el-tag type="primary" size="small">文件</el-tag> {{ message.content }}
                            </template>
                        </div>
                        <div class="message-time">
                            {{ message.sendTime }}
                            <el-button v-if="message.userNum === currentUser.number" icon="Delete" size="mini"
                                type="text" @click="deleteMessage(message.id)"></el-button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 输入区域 -->
        <div class="chat-input-area">
            <div class="input-container">
                <el-input v-model="inputMessage" class="message-input" placeholder="输入消息..."
                    @keyup.enter="sendMessage"></el-input>
                <el-button type="primary" @click="sendMessage">发送</el-button>
            </div>
        </div>

        <!-- 成员列表弹窗 -->
        <el-dialog title="群成员" v-model="showMemberList" width="400px">
            <el-input v-model="memberSearch" placeholder="搜索通知" clearable class="search-input"></el-input>
            <div>
                <div v-for="member in filteredMembers">
                    <el-avatar :src="member.avatar" size="small">{{ member.name.charAt(0) }}</el-avatar>
                    <div class="member-info">
                        <div class="member-name">{{ member.userNum }}</div>
                        <div class="member-role">{{ member.identity }}</div>
                    </div>
                </div>
            </div>
        </el-dialog>

        <!-- 通知列表弹窗 -->
        <el-dialog title="通知列表" v-model="showNoticeList" width="600px" class="notice-dialog">
            <el-input v-model="noticeSearch" placeholder="搜索通知" clearable class="search-input"></el-input>
            <div class="notice-list">
                <div v-for="notice in filteredNotices" :key="notice.id" class="notice-item"
                    :class="{ 'unread-notice': !notice.read, 'pinned-notice': notice.isPinned === 1 }"
                    @click="markNoticeAsRead(notice.id)">
                    <div class="notice-header">
                        <h4>
                            {{ notice.title }}
                            <el-tag v-if="notice.isPinned === 1" size="mini" type="warning">置顶</el-tag>
                        </h4>
                        <span class="notice-time">{{ notice.time }}</span>
                    </div>
                    <div class="notice-content">{{ notice.content }}</div>
                    <div class="notice-footer">
                        <span class="notice-sender">{{ notice.userName }}</span>
                        <el-tag v-if="notice.noticeType === 2" type="danger">紧急</el-tag>
                        <span class="read-count">已读: {{ notice.readCount }}</span>
                    </div>
                </div>
            </div>
        </el-dialog>

        <!-- 文件列表弹窗 -->
        <el-dialog title="文件列表" v-model="showFileList" width="600px" class="file-list-dialog">
            <el-input v-model="fileSearch" placeholder="搜索文件" clearable class="search-input"></el-input>
            <div class="file-list">
                <div v-for="file in filteredFiles" :key="file.id" class="file-item">
                    <el-icon class="file-icon">
                        <Document />
                    </el-icon>
                    <div class="file-info">
                        <div class="file-name">{{ file.fileName }}</div>
                        <div class="file-meta">
                            <span>{{ (file.fileSize / 1024 / 1024).toFixed(1) }}MB</span>
                            <span>上传者: {{ file.userNum }}</span>
                            <span>{{ formatTime(file.createdAt) }}</span>
                        </div>
                    </div>
                    <el-button type="text" @click="downloadFile(file.id)">下载</el-button>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
    import {
        ref,
        reactive,
        computed,
        onMounted,
        nextTick,
        onUnmounted
    } from 'vue';
    import {
        useRouter,
        useRoute
    } from 'vue-router';
    import {
        ElMessage
    } from 'element-plus';
    import {
        ArrowLeft,
        More,
        Document,
        Bell,
        Close,
        Delete
    } from '@element-plus/icons-vue';
    import webSocketService from '../../../../utils/user-group-chat/webSocket.js';
    import {
        getMessages,
        getFiles,
        getNotifications,
        markNotificationReadCount,
        deleteMessage as deleteMessageApi,
        getClassMembers
    } from '../../../../api/user-group-chat/user-group-chat.js';
    import {
        useLoginStore
    } from '../../../../stores/index.js';

    const router = useRouter();
    const uploadRef = ref(null);
    const loginStore = useLoginStore();

    // 控制弹窗显示
    const showMemberList = ref(false);
    const showFileList = ref(false);
    const showNoticeList = ref(false);

    // 输入消息
    const inputMessage = ref('');

    // 上传相关
    const uploadHeaders = ref({
        Authorization: `Bearer ${localStorage.getItem('token')}`
    });
    const uploadFileList = ref([]);

    // 搜索相关
    const noticeSearch = ref('');
    const fileSearch = ref('');
    const memberSearch = ref('')

    // 当前用户（家长）信息
    const currentUser = ref({
        number: loginStore.user.number,
        name: loginStore.user.name,
        avatar: loginStore.user.avatar,
        role: loginStore.user.role
    });

    // 群组信息
    const groupInfo = ref({
        classId: parseInt(router.currentRoute.value.params.classId),
        className: '未命名班级',
        members: []
    });

    // 消息列表
    const messages = ref([]);
    const notices = ref([]);
    const files = ref([]);
    const members = ref([]);

    // 过滤后的通知
    const filteredNotices = computed(() => {
        let filtered = notices.value.filter(notice =>
            notice.title.includes(noticeSearch.value) ||
            notice.content.includes(noticeSearch.value)
        );
        // 按置顶状态降序 + 时间降序排序
        filtered.sort((a, b) => {
            if (a.isPinned !== b.isPinned) {
                return b.isPinned - a.isPinned; // 置顶通知在前
            }
            return new Date(b.time) - new Date(a.time); // 最新通知在前
        });
        return filtered;
    });

    // 在 filteredNotices 下方添加
    const filteredFiles = computed(() => {
        return files.value.filter(file =>
            // 按文件名搜索（根据实际字段调整，比如 fileName 可能是 name）
            file.fileName.includes(fileSearch.value) ||
            file.userNum.includes(fileSearch.value)
        );
    });
    
    const filteredMembers = computed(() => {
        console.log('member======>', members)
        return members.value.filter(member =>
            member.userNum.includes(memberSearch.value))
    })


    // 返回
    const back = () => {
        router.back();
    };

    // 获取发送者姓名
    const getSenderName = (userNum) => {
        // 如果是当前用户，显示自己的名字
        if (userNum === currentUser.value.number) {
            return currentUser.value.name;
        }

        // 从群成员中查找对应的用户名
        const member = groupInfo.value.members.find(m => m.userNum === userNum);
        return member ? member.name : `用户${userNum}`;
    };

    // 发送消息
    const sendMessage = () => {
        if (!inputMessage.value.trim()) return;

        const messageContent = inputMessage.value.trim();
        const newMessage = {
            id: Date.now(),
            classId: groupInfo.value.classId,
            userNum: currentUser.value.number,
            type: 'text',
            content: messageContent,
            sendTime: new Date().toISOString(),
            status: 0,
            time: formatTime(new Date().toISOString()),
            avatar: currentUser.value.avatar
        };

        // 通过WebSocket发送消息
        webSocketService.send('/app/groupChat.sendMessage.' + groupInfo.value.classId, {
            classId: groupInfo.value.classId,
            userNum: currentUser.value.number,
            content: messageContent,
            type: 'text',
            sendTime: new Date().toISOString()
        });
        // 清空输入框
        inputMessage.value = '';
        // 滚动到底部
        scrollToBottom();
    };

    // 处理接收到的消息
    const handleReceivedMessage = (message) => {
        const formattedMessage = {
            ...message,
            time: formatTime(message.sendTime),
            avatar: message.avatar || `https://picsum.photos/seed/${message.userNum}/100/100`
        };

        messages.value.push(formattedMessage);
        scrollToBottom();
    };

    // 滚动到底部
    const scrollToBottom = () => {
        nextTick(() => {
            const chatContent = document.querySelector('.chat-content');
            chatContent.scrollTop = chatContent.scrollHeight;
        });
    };

    // 下载文件
    // 文件操作事件
    const downloadFile = (fileId) => {
        try {
            // 1. 根据fileId找到当前要下载的文件
            const targetFile = files.value.find(file => file.id === fileId);
            if (!targetFile) { // 若未找到文件，提示错误
                ElMessage.error('未找到该文件，无法下载');
                return;
            }

            // 2. 获取文件的真实下载URL和文件名
            const fileUrl = targetFile.filePath;
            const fileName = targetFile.fileName || '未知文件名';

            console.log('fileUrl', fileUrl);

            if (!fileUrl) { // 若文件URL
                ElMessage.error('文件地址无效，无法下载');
                return;
            }

            // 3. 声明并创建<a>标签（修复a未定义的核心）
            const a = document.createElement('a');
            a.href = fileUrl; // 设置文件下载地址
            a.download = fileName; // 设置下载后的文件名
            a.target = '_blank'; // 避免部分浏览器拦截下载

            // 4. 触发下载（需将a标签临时添加到DOM中，部分浏览器要求DOM存在才能触发点击）
            document.body.appendChild(a);
            a.click(); // 模拟点击下载

            // 5. 下载后清理DOM（移除临时创建的a标签）
            document.body.removeChild(a);
            ElMessage.success('文件开始下载');
        } catch (error) {
            // 捕获异常，避免页面崩溃
            ElMessage.error('下载失败，请稍后重试');
            console.error('文件下载错误：', error);
        }
    };

    // 删除消息
    const deleteMessage = async (messageId) => {
        try {
            await deleteMessageApi(messageId);
            const msgIndex = messages.value.findIndex(msg => msg.id === messageId);
            if (msgIndex !== -1) {
                messages.value.splice(msgIndex, 1);
                ElMessage.success('消息已删除');
            }
        } catch (error) {
            ElMessage.error('消息删除失败');
        }
    };

    // 标记通知为已读
    const markNoticeAsRead = async (noticeId) => {
        try {
            await markNotificationReadCount(noticeId);
            const noticeIndex = notices.value.findIndex(notice => notice.id === noticeId);
            if (noticeIndex !== -1 && !notices.value[noticeIndex].read) {
                notices.value[noticeIndex].read = true;
                notices.value[noticeIndex].readCount++;
            }
        } catch (error) {
            ElMessage.error('标记已读失败');
        }
    };

    // 格式化时间
    const formatTime = (timeStr) => {
        return new Date(timeStr).toLocaleString('zh-CN', {
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
        });
    };

    // 加载数据
    const loadData = async () => {
        try {
            // 获取历史消息
            const msgRes = await getMessages(groupInfo.value.classId);
            if (msgRes != null) {
                // .map格式化消息数据  ...msg保留原有数据
                messages.value = msgRes.map(msg => ({
                    ...msg
                }));
            }
            scrollToBottom();
        } catch (error) {
            ElMessage.error('数据加载失败');
            console.error(error);
        }
    };

    const loadNoticeRes = async () => {
        showNoticeList.value = true
        const noticeRes = await getNotifications(groupInfo.value.classId);
        if (noticeRes != null) {
            notices.value = noticeRes.map(notice => reactive({
                ...notice
            }));
        }
    }

    const loadFiles = async () => {
        showFileList.value = true
        const fileRes = await getFiles(groupInfo.value.classId);
        if (fileRes != null) {
            files.value = fileRes;
        }
    }
    
    const loadMember = async () => {
        showMemberList.value = true
        const memberRes = await getClassMembers(groupInfo.value.classId);
        console.log("memberRes===>",memberRes);
        if (memberRes != null) {
            members.value = memberRes;
            console.log(members.value);
        }
    }

    // 页面加载时连接WebSocket并订阅
    onMounted(() => {
        loadData();

        const topic = `/topic/class.${groupInfo.value.classId}`;
        webSocketService.connect().then(() => {
            webSocketService.subscribe(topic, handleReceivedMessage);
        });
    });

    // 页面卸载时断开连接
    onUnmounted(() => {
        webSocketService.disconnect();
    });
</script>

<style scoped>
    @import '../../../../styles/groupChat.css';
</style>